package com.yxh.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.wordnik.swagger.annotations.ApiImplicitParam;
import com.wordnik.swagger.annotations.ApiImplicitParams;
import com.yxh.common.annotation.Authorization;
import com.yxh.pojo.*;
import com.yxh.service.PositionService;
import com.yxh.service.ViciousService;
import com.yxh.util.DateUtils;
import com.yxh.util.Response;
import com.yxh.util.SnowflakeIdWorker;
import com.yxh.util.TaskCode;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;

import java.util.*;

import static com.yxh.util.APIErrorCode.SUCCESS;

/**
 * Created by asus on 2018/6/12.
 * 到岗到位
 */
@Scope("prototype")
@RestController
@RequestMapping(value = "/position")
public class PositionController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(PositionController.class);
    private Response response;


    @Autowired
    private PositionService positionService;


    @Autowired
    private ViciousService viciousService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;
    /**
     *到岗到位新增
     *
     * @param reportJson
     * @return
     */
    @PostMapping
    @Authorization
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
    })
    public Response saveReport(@RequestBody JSONObject reportJson) {

        Position p=new Position();
        String id=SnowflakeIdWorker.creatId();
        p.setPositionId(id);
        p.setWorkId(reportJson.getString("workId"));//日计划id
        p.setCheckSituation(reportJson.getString("checkSituation"));
        p.setImgId(reportJson.getString("imgId"));//
        p.setLoggedUser(reportJson.getString("loggedUser"));
        p.setAuditingId(reportJson.getString("auditingId"));
        List<Map> questions = JSONArray.toJavaObject(reportJson.getJSONArray("question"),List.class);
        int i;
        System.out.println(questions);
        if(questions==null||questions.size()==0){
             p.setState(TaskCode.STATE_MEG4.getDesc());
        }
        else
            i= positionService.insertQ(id,questions);
            i=positionService.save(p);



        response = Response.returnResponse(SUCCESS);

        return response;
    }

    /**
     *到岗到位個人代辦理列表
     *
     * @param
     * @return
     */

    @GetMapping("/user")
   // @Authorization
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
    })
    public Response getInformation(@RequestParam(required = false,name = "id") String id,
                                   @RequestParam(required = false, name = "mangerName") String mangerName,
                                   @RequestParam(required = false, name = "date") String date,
                                   @RequestParam(required = false,name = "loggedUser") String loggedUser,
                                   @RequestParam(required = false,name = "state") String  state,
                                   @RequestParam(required = false,name = "auditingName") String  auditingName,
                                   @RequestParam(required = false,name = "page")String page,
                                   @RequestParam(required = false,name = "pageSize")String pageSize) {
        Integer limit;
        Integer offset;
        try {
            limit = Integer.parseInt(page);
            offset = Integer.parseInt(pageSize);
        } catch (Exception e) {
            limit = 1;
            offset = 10;
        }

        Map<String,Object> map=new  HashMap<String,Object>();
        map.put("auditingId",id);//指定审核人
        map.put("mangerName",mangerName);
        map.put("date",date);
        map.put("loggedUser",loggedUser);
        map.put("auditingName",auditingName);
        map.put("state",state);
        PageInfo pageInfo = positionService.getList(map, limit, offset);
        response = Response.returnResponse(SUCCESS);
        response.setData(pageInfo);
        return response;
    }

    /**
     *到岗到位個人代辦 詳情
     *
     * @param
     * @return
     */
    @GetMapping("/{id}")
    // @Authorization
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
    })
    public Response getInformation(@PathVariable(value = "id") String id) {

        Map<String,Object> position = positionService.getByPositionId(id);
        response = Response.returnResponse(SUCCESS);
        response.setData(position);
        return response;
    }

    /**
     *到岗到位個人代辦 审核
     *
     * @param
     * @return
     */
    @PostMapping("/auditing")
    @Authorization
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
    })
    public Response auditing(@RequestBody JSONObject reportJson) {
        int i=0;
        String log= reportJson.getString("loggedUser"),//指定下个处理人
                positionId= reportJson.getString("positionId"),img = null;//获取到岗到位id
        List<Map> questions = JSONArray.toJavaObject(reportJson.getJSONArray("question"),List.class);
        Position p =new Position();
        p.setPositionId(positionId);
        if(questions==null){
            p.setState("已完成");
        }
        else
            for(Map map:questions){

                String f=map.get("state").toString(),
                        m=map.get("questionDescribe").toString(),
                        id=SnowflakeIdWorker.creatId();
                if(map.get("imgsId")!=null){
                    id=map.get("imgsId").toString();//图片外链接id  不为空时 也可作为新的缺陷id
                    img=map.get("imgsId").toString();
                }

                History h=new History(); //存历史记录
                h.setUserid(log);
                h.setViciousId(id);



                h.setUnitId(reportJson.getString("unitId"));

                h.setDate(DateUtils.getDate());

                if(f.equals("2")){//有问题

                    String nextId=map.get("auditingId").toString();
                    Vicious v=new Vicious();//创建缺陷单

                    v.setViciousId(id);
                    v.setDay(new Date());
                    v.setViciousLevel(map.get("viciousLevel").toString());
                    v.setLoggedUser(log);
                    v.setProjectId(reportJson.getString("projectId"));//工程id
                    v.setProjectName(reportJson.getString("projectName"));
                    v.setArea(reportJson.getString("area"));
                    v.setImgsUrl(img);
                    v.setViciousCode(map.get("viciousCode").toString());
                    v.setViciousDescribe(m);
                    v.setViciousUser(log);
                    v.setStatu("整改中");
                    v.setUserId(nextId);
                    v.setViciousType(map.get("questionType").toString());

                    p.setState("缺陷整改中");
                    //保存缺陷单

                    i=viciousService.save(v);


               /* if(i==0){
                   throw
                }*/
                    //启动流程

                    Map<String,Object> variables = new HashMap<String, Object>();
                    variables.put("viciousId",id);//流程缺陷单
                    variables.put("positionId",positionId);//到岗到位单
                    variables.put("user",log);//指定审核人
                    variables.put("code",map.get("viciousCode"));
                    ProcessInstance pi =runtimeService.startProcessInstanceByKey("faultProcess",variables);
                    h.setOperationName("到岗到位缺陷录入");
                    h.setPresideId(log);
                    //h.setComment(m);
                    i=viciousService.insertHistroy(h);//记录每次操作流程提供的数据
                    Task task = taskService.createTaskQuery().processInstanceId(pi.getProcessInstanceId()).singleResult();
                    String processInstacnId = task.getProcessInstanceId();
                    Authentication.setAuthenticatedUserId("到岗到位");//
                    taskService.addComment(task.getId(), processInstacnId, "到岗到位缺陷录入");
                    taskService.complete(task.getId(),variables);
                    //先把审核第一步走完

                    h.setComment(m);
                    h.setOperationName("业主项目部审核");
                    h.setState("有缺陷");
                    h.setImgId(img);
                    h.setPresideId(nextId);

                    Task tasks = taskService.createTaskQuery().processInstanceId(pi.getProcessInstanceId()).singleResult();

                    Map<String,Object> variables1 = new HashMap<String, Object>();

                    variables1.put("user1", nextId);
                    variables1.put("meg", "2");

                    String processInstacnIds = tasks.getProcessInstanceId();
                    Authentication.setAuthenticatedUserId("业主项目部审核");//
                    taskService.addComment(tasks.getId(), processInstacnIds, "审核有缺陷");
                    taskService.complete(tasks.getId(),variables1);

                }
                else{
                    h.setState("无缺陷");


                    p.setState("已完成");
                }
                i=viciousService.insertHistroy(h);//记录每次操作流程提供的数据

            }
        //更新到岗到位报表 状态
        i= positionService.update(p);
        response = Response.returnResponse(SUCCESS);

        return response;
    }
}